package com.guavamail.smtp.command.impl;

import java.io.IOException;

import org.apache.mina.core.session.IoSession;

import com.guavamail.smtp.SMTPContext;
import com.guavamail.smtp.SessionStatus;
import com.guavamail.smtp.command.AbstractCommand;

public class RCPT extends AbstractCommand {
	public RCPT() {
		super("RCPT", "");
	}

	@Override
	public void execute(String commandString, IoSession ioSession, SMTPContext ctx) throws IOException {
		SessionStatus sessionStatus = ctx.getSessionStatus();
		if (!sessionStatus.getHasSeenHelo()) {
			sendResponse(ioSession, "503 Error: send HELO/EHLO first");
		}

		int max = ctx.getSMTPServerConfig().getMaxRecipients();
		if (max > -1 && sessionStatus.getRecipientCount() >= max) {
			sendResponse(ioSession, "452 Too many recipients");
			return;
		}

		String args = getArgPredicate(commandString);
		if (!args.toUpperCase().startsWith("TO:")) {
			sendResponse(ioSession, "501 Syntax: RCPT TO: <address> Error in parameters: \"" + args + "\"");
			return;
		} else {
			String recipientAddress = extractEmailAddress(args, 3);
			sessionStatus.addRecipient(recipientAddress);
			sendResponse(ioSession, "250 Ok");
		}
	}

}
